package com.tuomaxu.servlet;

import com.tuomaxu.factory.BeanFactory;
import com.tuomaxu.factory.ProxyFactory;

import com.tuomaxu.pojo.Result;
import com.tuomaxu.service.TransferService;

import com.tuomaxu.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "transferServlet",urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    private ProxyFactory proxyFactory = (ProxyFactory)BeanFactory.getBean("com.tuomaxu.factory.ProxyFactory");
    private TransferService transferService =(TransferService) proxyFactory.getCglibProxy(BeanFactory.getBean("com.tuomaxu.service.impl.TransferServletImpl"));

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardStr = req.getParameter("fromCardId");
        String toCardStr = req.getParameter("toCardId");
        String moneyStr = req.getParameter("money");
        Integer fromCardId = Integer.valueOf(fromCardStr);
        Integer toCardId = Integer.valueOf(toCardStr);
        Integer money = Integer.valueOf(moneyStr);

        Result result = new Result();

        try {
            transferService.transfer(fromCardId,toCardId,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }


        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));


    }
}
